<?php

App::uses('AppController', 'Controller');

/**
 * Subscriptions Controller
 *
 * @property Subscription $Subscription
 */
class SubscriptionsController extends AppController {

    public $components = array('IpnHandler');

    public function beforeFilter() {
        parent::beforeFilter();
        
        /* if (isset($this->Auth)) {
            $this->Auth->allow('process');
        }*/
        if (isset($this->Security) && $this->action == 'process') {
            $this->Security->validatePost = false;
            $this->Security->csrfCheck = false;
        }
        
        
        $this->Auth->allow('*');
    }

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->Subscription->recursive = 0;
        $this->set('subscriptions', $this->paginate());
        
        $data['Payment']['payer_email'] = 'sophy.prak@gmail.com';
       // $this->completeTransaction($data);
        
       /* $this->Subscription->buildAssociationsFromIPN(array(
                'item_number' => 'SUB3-41-45', 
                'mc_gross' => 100, 
                "payment_status" => "Completed",
                "txn_id" => "3BD712374N8406005ww",
                'business' => 'sophy._1339907978_biz@gmail.com'
            )); */
        
        //echo $this->Subscription->Payment->checkIPNID('3BD712374N8406005');
        
    }

    public function plans() {
        $this->setPageTitle(__('Select Plan Option'));
        $terms = $this->Subscription->SubscriptionTerm->find('all'); 
        
        $plan3 = '';
        $plan6 = '';
        $plan12 = '';
        
        foreach($terms as $tm) {
            if ($tm['SubscriptionTerm']['term'] == 3) {
               $plan3 = $tm['SubscriptionTerm']['price'];
            }
            if ($tm['SubscriptionTerm']['term'] == 6) {
                $plan6 = $tm['SubscriptionTerm']['price'];
            }
            if ($tm['SubscriptionTerm']['term'] == 12) {
                $plan12 = $tm['SubscriptionTerm']['price'];
            }
        }
        $this->set(compact('plan3', 'plan6', 'plan12'));
        
    }

    /**
     * view method
     *
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        $this->Subscription->id = $id;
        if (!$this->Subscription->exists()) {
            throw new NotFoundException(__('Invalid subscription'));
        }
        $this->set('subscription', $this->Subscription->read(null, $id));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->Subscription->create();
            if ($this->Subscription->save($this->request->data)) {
                $this->Session->setFlash(__('The subscription has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The subscription could not be saved. Please, try again.'));
            }
        }
        $users = $this->Subscription->User->find('list');
        $subscriptionTerms = $this->Subscription->SubscriptionTerm->find('list');
        $this->set(compact('users', 'subscriptionTerms'));
    }

    /**
     * edit method
     *
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        /*
          $this->Subscription->id = $id;
          if (!$this->Subscription->exists()) {
          throw new NotFoundException(__('Invalid subscription'));
          }
          if ($this->request->is('post') || $this->request->is('put')) {
          if ($this->Subscription->save($this->request->data)) {
          $this->Session->setFlash(__('The subscription has been saved'));
          $this->redirect(array('action' => 'index'));
          } else {
          $this->Session->setFlash(__('The subscription could not be saved. Please, try again.'));
          }
          } else {
          $this->request->data = $this->Subscription->read(null, $id);
          }
          $users = $this->Subscription->User->find('list');
          $subscriptionTerms = $this->Subscription->SubscriptionTerm->find('list');
          $this->set(compact('users', 'subscriptionTerms'));
         */
    }

    /**
     * processPayment method
     * When you choose Paypal method
     * 
     * @param int $id user id
     */
   /* public function processPayment($id) {
        $this->Subscription->User->id = $id;
        if (!$this->Subscription->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        } else {
            $data = $this->Session->read('paypal_payment_data_' . $id);
            if (!empty($data)) {
                $this->set('data', $data);
                $this->loadModel('Setting');
                $this->set('price', $this->Setting->getPricePlan($data['User']['plan']));
            } else {
                $this->Session->setFlash(__('Session timeout.'));
                $this->redirect('/');
            }
        }
    }*/
/**
 * Complete payment or cancel
 * 
 * @param type $complete 
 */
    public function completePayment($complete = 0) {
        
    }
    public function process() {
        $this->autoLayout = false;
        $this->autoRender = false;
        
        if ($this->Subscription->is_valid($_POST)) {
           $notification = $this->Subscription->buildAssociationsFromIPN($_POST);
           if (( 
                   isset($notification['Payment']['actived']) && 
                   isset($notification['Payment']['payment_status'])) &&
                   ($notification['Payment']['actived'] == 0 &&
                   $notification['Payment']['payment_status'] == 'Completed')
           ) {
                $this->completeTransaction($notification);
            } else {
		$this->log('IPN request twice or complete payment', 'paypal');
            }
		   
        }
        
        $this->redirect('/');
         
        
    }
    
    /**
     * __processTransaction is a private callback function used to log a verified transaction
     * @access private
     * @param String $txnId is the string paypal ID and the id used in your database.
     */
    private function __processTransaction($data) {
        $this->log("Processing Trasaction: ". $data['Payment']['txn_id'], 'paypal');
        //Put the afterPaypalNotification($txnId) into your app_controller.php
       // $this->afterPaypalNotification($txnId);
        
        
    }
    
    protected function completeTransaction($data, $options =  array()) {
  
          $defaults = array(
            'from' => Configure::read('App.defaultEmail'),
            'subject' => __('Thank you for your paypal transaction'),
            'template' => 'paypal',
            'layout' => 'default',
              'log' => false
              );

        $options = array_merge($defaults, $options);
        $Email = $this->_getMailInstance();
        
        $Email->to($data['Payment']['payer_email'])
                    ->from($options['from'])
                    ->subject($options['subject'])
                    ->cc(Configure::read('App.adminEmail'))
                    ->template($options['template'], $options['layout'])
                    ->viewVars(array(
                        'model' => 'Payment',
                        'data' => $data))
                    ->send();
        
        //Confirm admin
         $Email->to(Configure::read('App.adminEmail'))
                    ->from($options['from'])
                    ->subject('Completed Paypal Payment')
                    ->template('paypal_completed', $options['layout'])
                    ->viewVars(array(
                        'model' => 'Payment',
                        'data' => $data))
                    ->send();
         
        $this->log('Sent mail by IPN'. $data['Payment']['payer_email'], 'paypal');
        
        
    }
    /**
     * Returns a CakeEmail object
     *
     * @return object CakeEmail instance
     * @link http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
     */
    protected function _getMailInstance() {
        App::uses('CakeEmail', 'Network/Email');
        return new CakeEmail();
    }
    /**
     * ADMIN SECTION
     * 
     */
    public function admin_index($status = 1) {
        $title = __('Subscriber');
        switch ($status) {
            case 1:
                $title = __('Active Subscribers');
                break;
            case 0:
                $title = __('Deactive Subscribers');
                break;
            case -1:
                $title = __('Expired Subscribers');
                break;
            case 2:
                $title = __('Pending Subscribers');
                break;
        }
        $this->Subscription->recursive = 0;
        $this->paginate = array(
            'conditions' => array('Subscription.active' => $status, 'Subscription.deleted' => 0)
        );
        $this->set('title', $title);
        $this->set('subscriptions', $this->paginate());
    }

    public function admin_add() {
        $this->setPageTitle(__('Add Subscriber'));
        if ($this->request->is('post')) {

            if ($this->Subscription->existSubscribe($this->request->data['Subscription']['user_id'])) {
                $this->Session->setFlash(__('Member has been subscribed already. Please, try other member!'));
            } else {

                if ($this->Subscription->newSubscride(0, 0, $this->request->data)) {
                    $this->Session->setFlash(__('The subscription has been saved'));
                    $this->redirect(array('action' => 'index'));
                } else {
                    $this->Session->setFlash(__('The subscription could not be saved. Please, try again.'));
                }
            }
        }

        $users = $this->Subscription->User->find('list');
        $subscriptionTerms = $this->Subscription->SubscriptionTerm->find('list');
        $this->set(compact('users', 'subscriptionTerms'));
    }

    public function admin_changeStatus($id, $deactive = false) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Subscription->id = $id;
        if (!$this->Subscription->exists()) {
            throw new NotFoundException(__('Invalid subscription'));
        }
        if ($deactive) {
            if ($this->Subscription->saveField('active', 0)) {
                $this->Session->setFlash(__('Subscription deactived'));
                $this->redirect(array('action' => 'index', 'admin' => true));
            } else {
                $this->Session->setFlash(__('Subscription is not deactive.'));
            }
        } else {
            if ($this->Subscription->saveField('active', 1)) {
                $this->Session->setFlash(__('Subscription was actived'));
                $this->redirect(array('action' => 'index', 'admin' => true));
            } else {
                $this->Session->setFlash(__('Subscription is not active. '));
            }
        }


        $this->redirect(array('action' => 'index', 'admin' => true));
    }

    public function admin_delete($id) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Subscription->id = $id;
        if (!$this->Subscription->exists()) {
            throw new NotFoundException(__('Invalid subscription'));
        }

        if ($this->Subscription->saveField('deleted', 1)) {
            $this->Session->setFlash(__('Subscription deleted'));
            $this->redirect(array('action' => 'index', 'admin' => true));
        } else {
            $this->Session->setFlash(__('Subscription was not deleted'));
        }



        $this->redirect(array('action' => 'index', 'admin' => true));
    }

    public function admin_subscridePricePlan() {
        if ($this->request->is('post')) {
            $this->loadModel('Setting');
            //pr($this->request->data);
            foreach ($this->request->data['Subscription'] as $key => $val) {
                $data['Setting'] = array(
                    'key' => $key,
                    'value' => $val
                );
                $this->Setting->addNewSetting($data);
            }
        }
    }

    /**
     * admin_addSubscribe plan from user managment
     * 
     * @param int $userId User's ID
     */
    public function admin_addSubscribe($userId) {

        $this->setPageTitle(__('Add Subscriber'));
        if ($this->Subscription->existSubscribe($userId)) {
            $this->Session->setFlash(__('Member has been subscribed already.'));
            $this->redirect(array('controller' => 'users', 'action' => 'index', 'admin' => true));
        }
        if ($this->request->is('post')) {
            $this->Subscription->newSubscride(0, 0, $this->request->data);

            $this->redirect(array('controller' => 'users', 'action' => 'index', 'admin' => true));
        }

        $subscriptionTerms = $this->Subscription->SubscriptionTerm->find('list');
        $this->set(compact('userId', 'subscriptionTerms'));
    }
    public function admin_cleanExpired() {
            $this->Subscription->cleanExpired();
            $this->Session->setFlash(__('Expired subscribers has been cleaned.'));
            $this->redirect(array('action' => 'index', 'admin' => true));
	}
    public function admin_priceList() {
        $this->Subscription->SubscriptionTerm->recursive = -1;
        $terms = $this->Subscription->SubscriptionTerm->find('all'); 
        $this->set('terms', $terms);
    }
    
    public function admin_subscrideSetting() {
        $this->Subscription->SubscriptionTerm->recursive = -1;
        $terms = $this->Subscription->SubscriptionTerm->find('all'); 
        if ($this->request->is('post')) {
            foreach($this->request->data['Subscription'] as $key => $val) {
                $this->Subscription->SubscriptionTerm->id = $key;
                $this->Subscription->SubscriptionTerm->saveField('price', $val);
            }
            $this->redirect(array('action' => 'priceList', 'admin' => true));
        }
        $this->set('terms', $terms);
    }

}